package com.shop.job;

import com.shop.mapper.InFormMapper;
import com.shop.mapper.ScheduleMapper;
import com.shop.model.dto.ScheduleLog;
import com.shop.schedule.MyScheduler;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 计算月销量的定时器
 */
public class ComputeMothSale extends QuartzJobBean {
    @Resource
    private ScheduleMapper scheduleMapper;
    @Resource
    private InFormMapper inFormMapper;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        //开始时间
        Date startTime = new Date();
        String error = null;
        try {
            //获取所有的商家id
            List<Integer> merchantIds = scheduleMapper.getAllMerchantId();
            //获取每个商家本月的订单数量,并设置
            for (Integer id : merchantIds) {
                Calendar c = Calendar.getInstance();
                c.setTime(new Date());
                c.add(Calendar.MONTH, -1);
                Date lateMonth = c.getTime();
                int amount = scheduleMapper.getMonthSale(id, lateMonth, new Date());
                scheduleMapper.setMonthSale(id, amount);
            }
        } catch (Exception e) {
            e.printStackTrace();
            error = e.getMessage();
        }
        //结束时间
        Date endTime = new Date();
        ScheduleLog log = new ScheduleLog();
        int id = inFormMapper.getScheduleId(ComputeMothSale.class.getName());
        MyScheduler.insertLog(startTime, error, endTime, id, inFormMapper);
    }
}
